package com.wn.network.error

import android.net.ParseException
import com.google.gson.JsonParseException
import com.google.gson.stream.MalformedJsonException
import com.wn.common.provider.LoginServiceProvider
import com.wn.framework.helper.AppHelper
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import javax.net.ssl.SSLException

/**
 * @Author: wn
 * @Date: 2024/7/3 16:51
 * @Description: 异常 统一处理 工具类
 */
object ExceptionHandler {
  /**
   * 处理异常
   * @param t Throwable
   * @return ApiException
   */
  fun handleException(t: Throwable): ApiException = when (t) {
    is ApiException -> {
      if (t.errCode == ERROR.UN_LOGIN.code) {
        LoginServiceProvider.toLogin(AppHelper.getApplication())
      }
      t
    }
    is NoNetWorkException -> ApiException(ERROR.NETWORK_ERROR, t)
    is HttpException ->
      when (t.code()) {
        ERROR.UNAUTHORIZED.code -> ApiException(ERROR.UNAUTHORIZED, t)
        ERROR.FORBIDDEN.code -> ApiException(ERROR.FORBIDDEN, t)
        ERROR.NOT_FOUND.code -> ApiException(ERROR.NOT_FOUND, t)
        ERROR.REQUEST_TIMEOUT.code -> ApiException(ERROR.REQUEST_TIMEOUT, t)
        ERROR.GATEWAY_TIMEOUT.code -> ApiException(ERROR.GATEWAY_TIMEOUT, t)
        ERROR.INTERNAL_SERVER_ERROR.code -> ApiException(ERROR.INTERNAL_SERVER_ERROR, t)
        ERROR.BAD_GATEWAY.code -> ApiException(ERROR.BAD_GATEWAY, t)
        ERROR.SERVICE_UNAVAILABLE.code -> ApiException(ERROR.SERVICE_UNAVAILABLE, t)
        else -> ApiException(t.code(), t.message(), t)
      }
    is JsonParseException, is JSONException, is ParseException, is MalformedJsonException ->
      ApiException(ERROR.PARSE_ERROR, t)
    is ConnectException -> ApiException(ERROR.NETWORK_ERROR, t)
    is SSLException -> ApiException(ERROR.SSL_ERROR, t)
    is SocketException, is SocketTimeoutException -> ApiException(ERROR.TIMEOUT_ERROR, t)
    is UnknownHostException -> ApiException(ERROR.UNKNOWN_HOST, t)
    else -> // UNKNOWN -- code = 1000
      if (!t.message.isNullOrEmpty())
        ApiException(1000, t.message!!, t)
      else
        ApiException(ERROR.UNKNOWN, t)
  }
}